/** https://github.com/apache/rocketmq-clients/blob/golang/v5.1.3/golang/example/producer/normal/main.go */
package main

import (
	"context"
	"fmt"
	"gitee.com/zackeus/go-zero/core/logx"
	rmq_client "github.com/apache/rocketmq-clients/golang/v5"
	"github.com/apache/rocketmq-clients/golang/v5/credentials"
	"os"
	"strconv"
)

const (
	Topic = "test-topic"
	// Endpoint 多个封号分割
	Endpoint  = "192.168.137.31:8081"
	AccessKey = "rmq-admin"
	SecretKey = "baicaf5678#"
)

func main() {
	/* 日志输出至控制台 */
	os.Setenv(rmq_client.ENABLE_CONSOLE_APPENDER, "true")
	os.Setenv(rmq_client.CLIENT_LOG_LEVEL, "error")
	rmq_client.ResetLogger()
	/* Disable SSL. You can also use os.Setenv("rocketmq.client.enableSsl", "false"), but this should be configured before the program starts. */
	os.Setenv(rmq_client.CLIENT_ENABLE_SSL, "false")

	// In most case, you don't need to create many producers, singleton pattern is more recommended.
	producer, err := rmq_client.NewProducer(&rmq_client.Config{
		Endpoint: Endpoint,
		Credentials: &credentials.SessionCredentials{
			AccessKey:    AccessKey,
			AccessSecret: SecretKey,
		},
	},
		rmq_client.WithTopics(Topic), // 预加载的主题列表（优化性能）
	)
	if err != nil {
		logx.Error(err)
		return
	}
	// start producer
	if err := producer.Start(); err != nil {
		logx.Error(err)
		return
	}
	// graceful stop producer
	defer producer.GracefulStop()

	ctx := context.TODO()
	for i := 0; i < 3; i++ {
		// new a message
		msg := &rmq_client.Message{
			Topic: Topic,
			Body:  []byte("this is a message : " + strconv.Itoa(i)),
		}
		// set keys and tag
		msg.SetKeys("a", "b")
		msg.SetTag("ab")
		msg.SetMessageGroup("fifo")
		/* 同步发送消息 */
		resp, err := producer.Send(ctx, msg)
		if err != nil {
			logx.Error(err)
			return
		}
		for i := 0; i < len(resp); i++ {
			fmt.Printf("%#v\n", resp[i])
		}
	}
}
